package com.ddkj.netty.server.websocket.basiswebsocket;

import com.alibaba.fastjson.JSONObject;
import com.ddkj.netty.Setting;
import com.ddkj.netty.comm.JSONDateFormat;
import com.ddkj.netty.comm.JsonUtil;
import com.ddkj.netty.comm.ResultCodeEnum;
import com.ddkj.netty.redis.RedisUtil;
import com.ddkj.netty.server.TCPAddress;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


import java.util.HashMap;
import java.util.Map;

import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;


/**
 * WebSocketHandler
 */
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {

    private static final Log log = LogFactory.getLog(WebSocketServerHandler.class);

    //WEB_SOCKET_DDKJ_NETTY会话
    public static final AttributeKey<TCPAddress> WEB_SOCKET_KEY = AttributeKey.valueOf(Setting.WEB_SOCKET_DDKJ_NETTY);

    //存储channel
    public static Map<String, Channel> channelMap = new HashMap<>();

    private WebSocketServerHandshaker handshaker;

    @Override
    public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 传统的HTTP接入
        if (msg instanceof FullHttpRequest) {
            handleHttpRequest(ctx, (FullHttpRequest) msg);
        }
        // WebSocket接入
        else if (msg instanceof WebSocketFrame) {
            handleWebSocketFrame(ctx, (WebSocketFrame) msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        //获取用户数据
        TCPAddress tcpAddress = new TCPAddress(ctx.channel());
        log.info("----(WEB SOCKET 新用户)--(" + tcpAddress.getClientIP() + ")--上线----");
        ctx.channel().attr(WEB_SOCKET_KEY).set(tcpAddress);
        //存储channel
        channelMap.put(tcpAddress.getClientIP(), ctx.channel());

    }


    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        //获取用户数据
        TCPAddress tcpAddress = ctx.channel().attr(WEB_SOCKET_KEY).get();
        String clientIP = tcpAddress.getClientIP();//ip
        removeIP(clientIP);
        log.info("----WEB SOCKET  用户下线，ip:" + clientIP);
    }

    private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) throws Exception {

        log.info("-----headers()-------->" + req.headers().get("Upgrade"));

        // 如果HTTP解码失败，返回HHTP异常
        if (!req.decoderResult().isSuccess() || (!"websocket".equals(req.headers().get("Upgrade")))) {
            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
            return;
        }

        // 构造握手响应返回，本机测试
        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory("ws://localhost:" + Setting.WEB_SOCKET_PORT + "/ws", null, false);
        handshaker = wsFactory.newHandshaker(req);
        if (handshaker == null) {
            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
        } else {
            handshaker.handshake(ctx.channel(), req);
        }
    }

    /**
     * 处理请求
     */
    private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) {

        //返回数据
        String data = null;

        //获取用户数据
        TCPAddress tcpAddress = ctx.channel().attr(WEB_SOCKET_KEY).get();
        String clientIP = tcpAddress.getClientIP();//ip

        // 判断是否是关闭链路的指令
        if (frame instanceof CloseWebSocketFrame) {
            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
            return;
        }

        // 判断是否是Ping消息
        if (frame instanceof PingWebSocketFrame) {
            ctx.channel().writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
            return;
        }

        // 本例程仅支持文本消息，不支持二进制消息
        if (!(frame instanceof TextWebSocketFrame)) {
            throw new UnsupportedOperationException(String.format("%s frame types not supported", frame.getClass().getName()));
        }

        // 返回应答消息
        JSONDateFormat jsonDateFormat = null;
        String requestMessage = ((TextWebSocketFrame) frame).text();
        try {

            jsonDateFormat = JSONObject.parseObject(requestMessage, JSONDateFormat.class);
            String sender = jsonDateFormat.getSender();//发送者
            String recipient = jsonDateFormat.getRecipient();//消费者

            if (sender == null && recipient == null && StringUtils.isBlank(sender)) {
                //参数校验
                data = JSONObject.toJSONString(JsonUtil.getFailJsonObject("参数错误"));
                ctx.channel().writeAndFlush(new TextWebSocketFrame(data));
                return;
            }


            //进行存储判断
            String rSen = RedisUtil.get(Setting.DDKJ_NETTY_WEB_SOCKET_HEADER + sender);
            if (rSen == null || !rSen.equals(clientIP)) {

                //删除老的ip
                if (rSen != null && !rSen.equals(clientIP)) {
                    RedisUtil.remove(Setting.DDKJ_NETTY_WEB_SOCKET_HEADER + rSen);
                }

                //存储数据,清缓存时所用
                RedisUtil.set(Setting.DDKJ_NETTY_WEB_SOCKET_HEADER + sender, clientIP);
                RedisUtil.set(clientIP, Setting.DDKJ_NETTY_WEB_SOCKET_HEADER + sender);
            }

            if (recipient == null || StringUtils.isBlank(recipient)) {
                //向后台服务器返回数据
                data = JSONObject.toJSONString(JsonUtil.getResultJson(ResultCodeEnum.ONLINE));
                ctx.channel().writeAndFlush(new TextWebSocketFrame(data));
                return;
            }

            //缓存获取接收者
            String recip = RedisUtil.get(Setting.DDKJ_NETTY_WEB_SOCKET_HEADER + recipient);
            if (recip == null) {
                JSONObject jsonObject = JSONObject.parseObject(requestMessage);
                jsonObject.put("code", ResultCodeEnum.FAIL.getValue());
                jsonObject.put("msg", "接收者未在线或错误");
                jsonObject.remove("data");
                ctx.channel().writeAndFlush(new TextWebSocketFrame(jsonObject.toJSONString()));
                return;
            }

            //获取接收者Channel
            Channel getChannel = channelMap.get(recip);
            if (getChannel != null && getChannel.isActive()) {
                JSONObject jsonObject = JSONObject.parseObject(requestMessage);
                jsonObject.put("code", 202);
                jsonObject.put("msg", "receive");
                //发送消息
                getChannel.writeAndFlush(new TextWebSocketFrame(jsonObject.toJSONString()));

            } else {
                JSONObject jsonObject = JSONObject.parseObject(requestMessage);
                jsonObject.put("code", ResultCodeEnum.FAIL.getValue());
                jsonObject.put("msg", "客户端未在线");
                jsonObject.remove("data");
                ctx.channel().writeAndFlush(new TextWebSocketFrame(jsonObject.toJSONString()));
                log.info("----SOCKET 客户端--( 客户端未在线 )--客户端id为--" + recip);
                return;
            }

            //返回请求状态信息
            JSONObject jsonObject = JSONObject.parseObject(requestMessage);
            jsonObject.put("code", ResultCodeEnum.SUCCESS.getValue());
            jsonObject.put("msg", ResultCodeEnum.SUCCESS.getKey());
            jsonObject.remove("data");
            ctx.channel().writeAndFlush(new TextWebSocketFrame(jsonObject.toJSONString()));
            return;

        } catch (Exception e) {
            //参数校验
            data = JSONObject.toJSONString(JsonUtil.getFailJsonObject("参数错误或格式错误"));
            ctx.channel().writeAndFlush(new TextWebSocketFrame(data));
        }

    }

    private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) {

        // 返回应答给客户端
        if (res.getStatus().code() != 200) {
            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
            res.content().writeBytes(buf);
            buf.release();
            HttpUtil.setContentLength(res, res.content().readableBytes());
        }

        // 如果是非Keep-Alive，关闭连接
        ChannelFuture f = ctx.channel().writeAndFlush(res);
        if (!HttpUtil.isKeepAlive(req) || res.status().code() != 200) {
            f.addListener(ChannelFutureListener.CLOSE);
        }

    }


    //清除数据
    protected void removeIP(String ipURI) {

        String whos = RedisUtil.get(ipURI);

        if (whos != null) {
            RedisUtil.remove(whos);
        }
        RedisUtil.remove(ipURI);
        //清空存储Map
        channelMap.remove(ipURI);

    }


}